package com.power.handler;

import cn.hutool.json.JSONUtil;
import com.power.constant.Constant;
import com.power.model.TUser;
import com.power.result.R;
import com.power.service.RedisService;
import com.power.util.ResponseUtils;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @Author 海晨忆
 * @Des 退出成功的Handler
 * @Date 2025/8/7 9:35
 */
@Component
public class MyLogoutSuccessHandler implements LogoutSuccessHandler {
    @Autowired
    private RedisService redisService;

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        //退出成功，删除指定用户的jwt
        redisService.removeValue(Constant.REDIS_TOKEN_KEY + ((TUser) authentication.getPrincipal()).getId());
        R result = R.OK("退出成功");
        //数据转json字符串
        String jsonStr = JSONUtil.toJsonStr(result);
        //把数据写给前端
        ResponseUtils.write(response, jsonStr);
    }
}
